import threading
from tkinter import *
import pyfirmata
import time
import datetime

log_smoke_date = []

smoke_threshold_for_alarm = 0.02
board = pyfirmata.Arduino('/dev/cu.usbmodem14201')

it = pyfirmata.util.Iterator(board)
it.start()

redLed = board.get_pin('d:11:o')
greenLed = board.get_pin('d:9:o')
gas_sensor_data = board.get_pin('a:0:i')
buzzer = board.get_pin('d:6:o')
buzzer.mode = pyfirmata.PWM
buzzer.frequency = 440
statusValue = None
logDateTimeValue = None
didLog = False
isrunning = True

def checkSmokeDetector():
    global didLog
    global isrunning
    while(isrunning):
        try: 
            value = gas_sensor_data.read()
            if value is not None:
                if statusValue is not None:
                    statusValue.config(text = str(value))
                    
                if value > smoke_threshold_for_alarm:
                    redLed.write(1)
                    greenLed.write(0)
                    buzzer.write(1)
                    if didLog == False and logDateTimeValue is not None:
                        log_smoke_date.append(str(datetime.datetime.now()))
                        logValue = ""
                        for i in log_smoke_date:
                            logValue += i + '\n'
                        logDateTimeValue.config(text = logValue)
                        didLog = True
                else:
                    redLed.write(0)
                    greenLed.write(1)
                    buzzer.write(0)
                    didLog = False
        except:
            print("program end")
            isrunning = False

t1 = threading.Thread(target=checkSmokeDetector, args=())
t1.start()

def increaseSmokeRate():
    global smoke_threshold_for_alarm
    smoke_threshold_for_alarm += 0.0010
    smokeRateValue.config(text = str(smoke_threshold_for_alarm))

def decreaseSmokeRate():
    global smoke_threshold_for_alarm
    smoke_threshold_for_alarm -= 0.0010
    smokeRateValue.config(text = str(smoke_threshold_for_alarm))

root = Tk()
root.geometry("800x400")
root.title('AntiSmokeX')
w = Label(root, text='Smoke status')
w.grid(row=0)
statusValue = Label(root, text='value')
statusValue.grid(row=0, column = 1)

smokeRateTitle = Label(root, text='Smoke threshold for alarm')
smokeRateTitle.grid(row=1)
smokeRateValue = Label(root, text=str(smoke_threshold_for_alarm))
smokeRateValue.grid(row=1, column = 1)

b1= Button(root, text= "Increase smoke threshold for alarm", command=increaseSmokeRate)
b1.grid(row=2)
b2= Button(root, text= "Decrease smoke threshold for alarm", command=decreaseSmokeRate)
b2.grid(row=2,column = 1)

logDateTimeLabel = Label(root, text='History')
logDateTimeLabel.grid(row=3)
logDateTimeValue = Label(root, text=str(log_smoke_date))
logDateTimeValue.grid(row=3, column = 1)

root.mainloop()


